package com.hontech.bvapp2.ui.parts.heat

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import com.hontech.bvapp2.R
import com.hontech.bvapp2.device.cp.Heat
import com.hontech.bvapp2.ui.dialog.runProg
import com.hontech.bvapp2.ui.dialog.runProg2
import com.hontech.bvapp2.ui.view.LabelInput
import com.hontech.bvapp2.utils.hex8
import com.hontech.bvapp2.utils.onClick
import kotlinx.coroutines.delay

class HeatIceParts (context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_heat_ice, this)
        val ctrlBtn = view.findViewById<Button>(R.id.id_heat_ice_btn_ctrl)
        val liCmd2 = view.findViewById<LabelInput>(R.id.id_heat_ice_li_cmd2)
        val liData1 = view.findViewById<LabelInput>(R.id.id_heat_ice_li_data1)
        val liData2 = view.findViewById<LabelInput>(R.id.id_heat_ice_li_data2)

        val queryStatusBtn = view.findViewById<Button>(R.id.id_heat_ice_btn_query_status)

        ctrlBtn.onClick {
            runProg2("制冰机", "控制") {
                val cmd2 = liCmd2.textInt()
                val data1 = liData1.textInt()
                val data2 = liData2.textInt()
                val result = Heat.ice(cmd2, data1, data2)
                "返回:${result.cmd2.hex8()} ${result.data1} ${result.data2}"
            }
        }

        queryStatusBtn.onClick {
            runProg2("制冰机", "状态查询") {
                val msg = Heat.queryIceStatus()
                val msg2 = Heat.queryIceOtherStatus()
                "$msg\r\n$msg2"
            }
        }

        val liIceNum = view.findViewById<LabelInput>(R.id.id_heat_ice_li_num)
        val iceBtn = view.findViewById<Button>(R.id.id_heat_ice_btn_ice_num)

        iceBtn.onClick {
            runProg("出冰", "") {
                Heat.drawIce(liIceNum.textInt())
                while (true) {
                    val info = Heat.drawIceProg()
                    it.setMsg("${info.step}=>${info.num*2}g")
                    if (info.isFinish) {
                        break
                    }
                    delay(500)
                }
            }
        }

        val resetBtn = view.findViewById<Button>(R.id.id_heat_ice_btn_reset)
        val stopBtn = view.findViewById<Button>(R.id.id_heat_ice_btn_stop)
        val dropBtn = view.findViewById<Button>(R.id.id_heat_ice_btn_drop_water)

        resetBtn.onClick {
            runProg("复位", "复位") {
                Heat.iceReset()
            }
        }

        stopBtn.onClick {
            runProg("停机", "停机") {
                Heat.iceStop()
            }
        }

        dropBtn.onClick {
            runProg("排水", "排水") {
                Heat.iceDrop()
            }
        }
    }
}
